package com.cskaoyan.market.service;

import com.cskaoyan.market.db.domain.MarketAddress;
import com.cskaoyan.market.db.domain.MarketAddressExample;
import com.cskaoyan.market.db.mapper.MarketAddressMapper;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author XuFeiLong
 * @DATE: 2023/4/2
 * @TIME: 0:15
 */
@Service
public class WxAddressServiceImpl implements WxAddressService {

    @Autowired
    MarketAddressMapper addressMapper;

    /**
     * 把数据库中的地址列表全部读出来
     *
     * @return
     */
    @Override
    public List<MarketAddress> list() {
        MarketAddressExample addressExample = new MarketAddressExample();
        addressExample.or().andDeletedEqualTo(false);
        List<MarketAddress> result = addressMapper.selectByExample(addressExample);
        return result;
    }

    /**
     * 根据id查询出相应的地址信息
     *
     * @param id
     * @return
     */
    @Override
    public MarketAddress detail(Integer id) {
        MarketAddressExample addressExample = new MarketAddressExample();
        addressExample.or().andIdEqualTo(id);
        MarketAddress result = addressMapper.selectOneByExample(addressExample);
        return result;
    }

    /**
     * 先判断有没有, 没有的话插入, 有的话更新
     * 最后还要进行一次判断, 如果你默认地址了之后, 其他默认地址应该取消
     *
     * @param address
     * @return 返回插入或者更新后的id
     */
    @Override
    public int save(MarketAddress address) {
        // 如果你默认地址了之后, 其他默认地址应该取消
        if (address.getIsDefault() == true) {
            MarketAddressExample addressExample = new MarketAddressExample();
            addressExample.or().andIsDefaultEqualTo(true);
            MarketAddress marketAddress = new MarketAddress();
            marketAddress.setIsDefault(false);
            addressMapper.updateByExampleSelective(marketAddress, addressExample);
        }
        Integer id = address.getId();
        MarketAddressExample addressExample = new MarketAddressExample();
        addressExample.or().andIdEqualTo(id);
        MarketAddress marketAddress = addressMapper.selectOneByExample(addressExample);
        // 如果表中没有, 插入
        if (marketAddress == null) {
            addressMapper.insertSelective(address);
        } else {
            // 如果表中有, 更新
            addressMapper.updateByPrimaryKeySelective(address);
        }
        return id;
    }

    @Override
    public int delete(Integer id) {
        try {

            MarketAddress marketAddress = new MarketAddress();
            marketAddress.setDeleted(true);
            MarketAddressExample marketAddressExample = new MarketAddressExample();
            marketAddressExample.or().andIdEqualTo(id);
            addressMapper.updateByExampleSelective(marketAddress,marketAddressExample);
            return 200;
        }catch (Exception e){
            return 888;
        }
    }
}
